<?php

namespace Admin\Controller;

use Common\Common\AdminController;
use Common\Top;
use Common\Utils;
use Common\Sms;

class OrderTourController extends AdminController
{


    public function index()
    {
        if (IS_POST && IS_AJAX) {
            if (Utils::getFen(I('adjust')) != 0) {
                $edit_price = Utils::getFen(I('total')) + Utils::getFen(I('adjust'));
                $data['status'] = 1;
                $data['price'] = Utils::getYuan($edit_price);
                $this->ajaxReturn($data);
            }


            $orderInfo = D('OrderTour')->where('id=' . I('id', 0, 'int'))->field('agency_id,price_adjust,price_total,prepay_amount,state')->find();
            $mobile = M('agency')->where('id=' . $orderInfo['agency_id'])->field('id,mobile,weixinmp_openid')->find();

            $state = I('state');

            if ($state == Top::OrderStateClosed && $state && $orderInfo['state'] != Top::OrderStatePrepayed && $orderInfo['state'] != Top::OrderStateAllPayed) {
                $id = I('id');
                $stateData['state'] = Top::OrderStateClosed;
                M('order_tour')->where("id = '{$id}'")->save($stateData);

                //coupon
                $couponOrderId = I('id');
                $entityId = $mobile['id'];
                $couponStateUsed = Top::CouponStateUsed;

                $couponData['order_type'] = '0';
                $couponData['order_id'] = '0';
                $couponData['state'] = Top::CouponStateNotUsed;
                $couponData['memo'] = '';
                $couponInfo = M('promotion_coupon')->where("agency_id = '{$entityId}' && order_type = 1 && order_id = '{$couponOrderId}' && state = '{$couponStateUsed}'")->limit(1)->find();

                if ($couponInfo) {
                    $couponId = $couponInfo['id'];
                    M('promotion_coupon')->where("id = '{$couponId}'")->save($couponData);
                }
                //coupon

                $orderLogData['order_id'] = I('id');
                $orderLogData['user_id'] = session('user_id');
                $orderLogData['user_name'] = session('entity_name');

                if ($couponInfo) {
                    $orderLogData['content'] = "供应商" . $orderLogData['user_name'] . "关闭订单,1张500的代金券已返还";
                } else {
                    $orderLogData['content'] = "供应商" . $orderLogData['user_name'] . "关闭订单";
                }

                $orderLogData['create_time'] = date("Y-m-d H:i:s", time());
                $orderLogData['payable_total'] = intval($orderInfo['price_adjust'] + $orderInfo['price_total']);

                M('log_order_tour')->add($orderLogData);

                $data['status'] = 6;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            }

            if ((I('editstate') && (I('editstate') == Top::OrderStateWaitForPayment || I('editstate') == Top::OrderStatePrepayed)) || $orderInfo['state'] = Top::OrderStateWaitForPayment) {
                if ($orderInfo['state'] == Top::OrderStateNotSubmitted) {
                    $data['status'] = 2;
                    $data['msg'] = '当前订单没有提交';
                    $this->ajaxReturn($data);
                } else if ($orderInfo['state'] == Top::OrderStateClosed) {
                    $data['status'] = 3;
                    $data['msg'] = '当前订单已关闭';
                    $this->ajaxReturn($data);
                } else if ($orderInfo['state'] == Top::OrderStateCanceled) {
                    $data['status'] = 4;
                    $data['msg'] = '当前订单已取消';
                    $this->ajaxReturn($data);
                } else if ($orderInfo['state'] == Top::OrderStateAllPayed) {
                    $data['status'] = 5;
                    $data['msg'] = '当前订单已付款';
                    $this->ajaxReturn($data);
                } else {

                    if (!I('editstate') && I('editamount') < 0 && $orderInfo['price_total'] >= I('editamount') && !preg_match('/^[0-9]+([.]{1}[0-9]+){0,1}$/', I('editamount'))) {
                        return false;
                    } else {
                        $order = D('OrderTour')->orderEdit(I('id', 0, 'int'), I('editstate', 0, 'int'), Utils::getFen(I('edit_price')), Utils::getFen(I('editadjust')), Utils::getFen(I('editamount')), I('memo'));

                        if ($order) {
                            $orderInfo = D('OrderTour')->where('id=' . I('id', 0, 'int'))->field('price_adjust,price_total,prepay_amount,state,order_sn,create_time,tour_name')->find();

                            if ($orderInfo['prepay_amount'] == 0 || $orderInfo['prepay_amount'] == null) {
                                $orderLogData['order_id'] = I('id');
                                $orderLogData['user_id'] = session('user_id');
                                $orderLogData['user_name'] = session('entity_name');
                                $orderLogData['content'] = "供应商" . $orderLogData['user_name'] . "确认订单，等待付款";
                                $orderLogData['create_time'] = date("Y-m-d H:i:s", time());
                                $orderLogData['amount'] = intval($orderInfo['price_adjust']);
                                $orderLogData['payable_total'] = intval($orderInfo['price_adjust'] + $orderInfo['price_total']);
                                $orderLogData['memo'] = I('memo');

                                if ($orderLogData['amount'] < 0) {
                                    $orderLogData['amount'] = intval($orderInfo['price_adjust']);
                                } else {
                                    $orderLogData['amount'] = "+" . intval($orderInfo['price_adjust']);
                                }


                                M('log_order_tour')->add($orderLogData);
                                $content = "您的 ".$orderInfo['tour_name']." 订单已被产品供应商确认，请尽快付全款，全款金额：" . (Utils::getYuan($orderInfo['price_total'] + $orderInfo['price_adjust']));
                            } else {
                                $orderLogData['order_id'] = I('id');
                                $orderLogData['user_id'] = session('user_id');
                                $orderLogData['user_name'] = session('entity_name');
                                $orderLogData['create_time'] = date("Y-m-d H:i:s", time());
                                $orderLogData['amount'] = intval($orderInfo['price_adjust']);
                                $orderLogData['payable_total'] = intval($orderInfo['price_adjust'] + $orderInfo['price_total']);
                                $orderLogData['memo'] = I('memo');

                                if ($orderLogData['amount'] < 0) {
                                    $orderLogData['amount'] = intval($orderInfo['price_adjust']);
                                } else {
                                    $orderLogData['amount'] = "+" . intval($orderInfo['price_adjust']);
                                }

                                $payMent = intval($orderInfo['price_total'] + $orderInfo['price_adjust'] - $orderInfo['prepay_amount']);

                                $orderState = (int)$orderInfo['state'];

                                if ($orderState == Top::OrderStateWaitForPayment) {
                                    $orderLogData['content'] = "供应商" . $orderLogData['user_name'] . "确认订单，预付金额：" . Utils::getYuan($orderInfo['prepay_amount']);
                                    $content = "您的 ".$orderInfo['tour_name']." 订单已被产品供应商确认，请尽快付预付款，预付金额：" . Utils::getYuan($orderInfo['prepay_amount']);
                                } else {
                                    $orderLogData['content'] = "供应商" . $orderLogData['user_name'] . "确认订单，尾款金额：" . Utils::getYuan($payMent);
                                    $content = "您的 ".$orderInfo['tour_name']." 订单已被产品供应商确认，请尽快付尾款，尾款金额：" . Utils::getYuan($payMent);
                                }

                                M('log_order_tour')->add($orderLogData);
                            }

                            $template=array(
                                'touser' => $mobile['weixinmp_openid'],
                                'template_id' => Utils::orderStateChangeTemplateId(),

                                'data'=>array(
                                    'first' => array('value' => urlencode($content),'color' => "#000"),
                                    'keyword1' => array('value' => urlencode($orderInfo['order_sn']),'color' => "#000"),
                                    'keyword2' => array('value' => urlencode(Utils::getYuan($orderInfo['price_total'] + $orderInfo['price_adjust'])),'color' => '#000'),
                                    'keyword3' => array('value' => urlencode($orderInfo['create_time']),'color' => '#000'),
                                    'keyword4' => array('value' => urlencode('供应商已确认,待付款'),'color' => '#000'),
                                )
                            );
                            $this->send_tpl($template);

                            Sms::Send($mobile['mobile'], $content, $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);
                            $data['status'] = 1;
                            $this->ajaxReturn($data);
                        } else {
                            $data['status'] = 0;
                            $data['msg'] = '确认订单失败';
                            $this->ajaxReturn($data);
                        }
                    }
                }
            } else if (I('state') && I('state') == Top::OrderStateClosed) {

                if (I('state') == Top::OrderStateClosed && $orderInfo['state'] == Top::OrderStateNotSubmitted) {
                    $data['status'] = 2;
                    $data['msg'] = '订单未提交，不能关闭';
                    $this->ajaxReturn($data);
                } else if (I('state') == Top::OrderStateClosed && $orderInfo['state'] == Top::OrderStateCanceled) {
                    $data['status'] = 3;
                    $data['msg'] = '订单已取消';
                    $this->ajaxReturn($data);
                } else if ($state['state'] == Top::OrderStatePrepayed || $orderInfo['state'] == Top::OrderStateAllPayed || $orderInfo['state'] == Top::OrderStatePrepayed) {
                    $data['status'] = 4;
                    $data['msg'] = '已付款不能关闭';
                    $this->ajaxReturn($data);
                } else if ($orderInfo['state'] == Top::OrderStateClosed) {
                    $data['status'] = 5;
                    $data['msg'] = '订单已关闭';
                    $this->ajaxReturn($data);
                } else {

                    $changestate = D('OrderTour')->orderOne(I('id', 0, 'int'), I('state', 0, 'int'));

                    if ($changestate) {
                        Sms::Send($mobile['mobile'], '您的订单已被产品供应商关闭，如有疑问，请登录登录系统查看', $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);
                        $data['status'] = 1;
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 0;
                        $this->ajaxReturn($data);
                    }
                }
            } else {
                $data['status'] = 6;
                $data['msg'] = '系统请求出错';
                $this->ajaxReturn($data);
            }
        } else {
            $providerId['id'] = session('entity_id');
            $providerCommissionRate = M('provider')->where($providerId)->field('id,commission_rate')->find();
            $dbRate = intval($providerCommissionRate['commission_rate']);

            $name = trim(I('get.name'));
            $entityId = session('entity_id');

            if (!empty($name)) {
                $where = "provider_id = '{$entityId}' && state > 1 && (agency_name like '%%$name%%' || tour_name like '%%$name%%')";
            } else {
                $where = "provider_id = '{$entityId}' && state > 1 ";
            }
            $order = "id desc ";
            $pageInfo = Utils::pages('order_tour', $where, C('PAGE_SET'), $order);
            foreach ($pageInfo['info'] as $key => $vo) {
                $arr[$key] = array(
                    'id' => $vo['id'],
                    'tour_name' => $vo['tour_name'],
                    'contact_person' => $vo['contact_person'],
                    'contact_phone' => $vo['contact_phone'],
                    'addr' => $vo['addr'],
                    'start_time' => $vo['start_time'],
                    'pickup_location' => $vo['pickup_location'],
                    'client_adult_count' => $vo['client_adult_count'],
                    'client_child_count' => $vo['client_child_count'],
                    'hotel_count' => $vo['hotel_count'],
                    'price_hotel' => $vo['price_hotel'],
                    'price_adjust' => $vo['price_adjust'],
                    'price_total' => $vo['price_total'],
                    'price_payable' => $vo['price_total'] + $vo['price_adjust'],
                    'prepay_amount' => $vo['prepay_amount'],
                    'prepay_amount_commission' => $vo['prepay_amount'] - Utils::CalcCommission($dbRate, $vo['prepay_amount']),
                    'price_payable_commission' => $vo['price_total'] + $vo['price_adjust'] - Utils::CalcCommission($dbRate, $vo['price_total'] + $vo['price_adjust']),
                    'state' => $vo['state'],
                    'create_time' => $vo['create_time'],
                    'agency_name' => $vo['agency_name'],
                    'memo' => $vo['memo'],
                    'prepay_time' => $vo['prepay_time'],
                    'fullpay_time' => $vo['fullpay_time'],
                );
            }
            $info = array(
                'info' => $arr,
                'page' => $pageInfo['page'],
            );

            $this->assign('name', $name);
            $this->info = $info['info'];
            $this->page = $info['page'];
            $this->display();
        }
    }


    /**
     * 订单取消
     */
    function orderCancel()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $where['id'] = I('id');
            $data['state'] = I('state');
            $orderInfo = M('order_tour')->where($where)->find();

            $entityId = $orderInfo['provider_id'];
            $entityType = Top::EntityTypeProvider;
            $operatorId = $orderInfo['provider_operator_id'];

            $providerBalance = Utils::getProviderInOperatorFrozenFen($entityType, $entityId, $operatorId);

            if ($orderInfo['fullpay_time'] != '') {
                $tourMoney = $orderInfo['price_total'] + $orderInfo['price_adjust'] - Utils::CalcCommission($orderInfo['commission_rate'], $orderInfo['price_total'] + $orderInfo['price_adjust']);
            } else {
                $tourMoney = $orderInfo['prepay_amount'] - Utils::CalcCommission($orderInfo['commission_rate'], $orderInfo['prepay_amount']);
            }

            if($data['state'] == 10){
                if ($providerBalance >= $tourMoney) {
                    $orderLogData['content'] = '供应商' . $orderInfo['provider_name'] . '审核订单取消,审核通过';
                }else{
                    $data['status'] = 0;
                    $data['msg'] = '冻结金额不足';
                    $this->ajaxReturn($data);
                }
            }

            if($data['state'] == 11){
                $orderLogData['content'] = '供应商' . $orderInfo['provider_name'] . '审核订单取消,拒绝取消';
            }

            $result = M('order_tour')->where($where)->save($data);

            $orderLogData['order_id'] = $orderInfo['id'];
            $orderLogData['user_id'] = $orderInfo['provider_id'];
            $orderLogData['user_name'] = $orderInfo['provider_name'];
            $orderLogData['amount'] = 0;
            $orderLogData['payable_total'] = $tourMoney;
            $orderLogData['create_time'] = date('Y-m-d H:i:s', time());

            $orderLogResult = M('log_order_tour')->add($orderLogData);

            if ($result && $orderLogResult) {
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }
        }
    }




    public function details()
    {
        $this->info = D('OrderTour')->orderDetails(I('sid'));
        $orderId = I('sid');
        $this->orderLog = M('log_order_tour')->where("order_id = '{$orderId}'")->select();
        $this->display();
    }

}
